var createError = require('http-errors');
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');
const ejs = require('ejs')
const cfg = require("./config/InUse")
import jwt from "./controller/util/jwt"
import Logs from "./controller/util/logs";
var app = express();
import "./controller/util/mongodb";

app.engine('.html', ejs.__express)
app.set('views', path.join(__dirname, '../views'));
app.set('view engine', 'ejs');

app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, '../public')));


app.all('*', (req, res, next) => {
    res.header("Access-Control-Allow-Origin", req.header('origin'));
    res.header("Access-Control-Allow-Credentials", 'true');
    res.header("Access-Control-Allow-Methods", "PUT,POST,GET,DELETE,OPTIONS");
    res.header("Access-Control-Max-Age", "1728000");
    res.header("Access-Control-Allow-Headers", "DNT,X-Mx-ReqToken,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type, Accept-Language, Origin, Accept-Encoding,Token");
    res.header("X-Powered-By", ' 3.2.1');
    next();
});

app.all('*', require("./routes/main"));

// catch 404 and forward to error handler
app.use(function (req: any, res: any, next: any) {
    next(createError(404));
});

// error handler
app.use(async function (err: any, req: any, res: any, next: any) {
    // set locals, only providing error in development
    if (err.status == 404) {
        res.status(404);
        res.render('error.html');
    } else {
        res.locals.message = err.message;
        res.locals.error = req.app.get('env') === 'development' ? err : { };

        // render the error page
        res.status(err.status || 500);
        await Logs.catchError(err);
        res.render('error.html');
    }
});

app.listen(cfg.serverUrl, (err: any) => {
    if (err) {
        Logs.catchError(err)
    }else{
        console.log(`server on 4000`)
    }
})
